<template>
  <div class="wash-quality">
    <!-- 搜索筛选 -->
    <el-card class="search-card">
      <el-form :model="searchForm" inline>
        <el-form-item label="订单号">
          <el-input v-model="searchForm.orderNo" placeholder="请输入订单号" clearable />
        </el-form-item>
        <el-form-item label="客户姓名">
          <el-input v-model="searchForm.customerName" placeholder="请输入客户姓名" clearable />
        </el-form-item>
        <el-form-item label="检查结果">
          <el-select v-model="searchForm.result" placeholder="请选择结果" clearable>
            <el-option label="合格" value="qualified" />
            <el-option label="不合格" value="unqualified" />
            <el-option label="待检" value="pending" />
          </el-select>
        </el-form-item>
        <el-form-item label="检查员">
          <el-input v-model="searchForm.inspector" placeholder="请输入检查员" clearable />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleSearch">查询</el-button>
          <el-button @click="handleReset">重置</el-button>
        </el-form-item>
      </el-form>
    </el-card>

    <el-card>
      <template #header>
        <div class="card-header">
          <span>质检管理</span>
          <el-button type="primary" @click="handleAdd">
            <el-icon><Plus /></el-icon>
            新建质检
          </el-button>
        </div>
      </template>
      
      <el-table :data="qualityList" v-loading="loading" border>
        <el-table-column prop="orderNo" label="订单号" />
        <el-table-column prop="customerName" label="客户" />
        <el-table-column prop="serviceType" label="服务类型">
          <template #default="{ row }">
            {{ getServiceTypeText(row.serviceType) }}
          </template>
        </el-table-column>
        <el-table-column prop="items" label="检查项目" min-width="150" />
        <el-table-column prop="inspector" label="检查员" />
        <el-table-column prop="result" label="检查结果">
          <template #default="{ row }">
            <el-tag :type="getResultType(row.result)">
              {{ getResultText(row.result) }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="score" label="质检评分" width="100">
          <template #default="{ row }">
            <span v-if="row.score">{{ row.score }}分</span>
            <span v-else>-</span>
          </template>
        </el-table-column>
        <el-table-column prop="checkTime" label="检查时间" width="160" />
        <el-table-column label="操作" width="200">
          <template #default="{ row }">
            <el-button type="text" @click="handleViewDetail(row)">详情</el-button>
            <el-button type="text" @click="handleEdit(row)" v-if="row.result === 'pending'">
              编辑
            </el-button>
            <el-button type="text" @click="handleRecheck(row)" v-if="row.result === 'unqualified'">
              重检
            </el-button>
            <el-button type="text" @click="handleComplete(row)" v-if="row.result === 'pending'">
              完成
            </el-button>
          </template>
        </el-table-column>
      </el-table>
      
      <!-- 分页 -->
      <div class="pagination">
        <el-pagination
          v-model:current-page="page.current"
          v-model:page-size="page.size"
          :total="page.total"
          :page-sizes="[10, 20, 50, 100]"
          layout="total, sizes, prev, pager, next, jumper"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </el-card>

    <!-- 质检详情对话框 -->
    <el-dialog v-model="detailDialogVisible" title="质检详情" width="700px">
      <el-descriptions :column="2" border>
        <el-descriptions-item label="订单号">{{ currentQuality.orderNo }}</el-descriptions-item>
        <el-descriptions-item label="客户姓名">{{ currentQuality.customerName }}</el-descriptions-item>
        <el-descriptions-item label="服务类型">{{ getServiceTypeText(currentQuality.serviceType) }}</el-descriptions-item>
        <el-descriptions-item label="检查员">{{ currentQuality.inspector }}</el-descriptions-item>
        <el-descriptions-item label="检查时间">{{ currentQuality.checkTime }}</el-descriptions-item>
        <el-descriptions-item label="检查结果">
          <el-tag :type="getResultType(currentQuality.result)">
            {{ getResultText(currentQuality.result) }}
          </el-tag>
        </el-descriptions-item>
        <el-descriptions-item label="质检评分">{{ currentQuality.score || '-' }}分</el-descriptions-item>
        <el-descriptions-item label="检查项目" :span="2">{{ currentQuality.items }}</el-descriptions-item>
        <el-descriptions-item label="问题描述" :span="2">{{ currentQuality.issues || '无' }}</el-descriptions-item>
        <el-descriptions-item label="备注" :span="2">{{ currentQuality.remark || '无' }}</el-descriptions-item>
      </el-descriptions>
      
      <!-- 质检图片 -->
      <div v-if="currentQuality.images && currentQuality.images.length" style="margin-top: 20px;">
        <h4>质检图片</h4>
        <el-image
          v-for="(image, index) in currentQuality.images"
          :key="index"
          :src="image"
          style="width: 100px; height: 100px; margin-right: 10px;"
          :preview-src-list="currentQuality.images"
          fit="cover"
        />
      </div>
    </el-dialog>

    <!-- 质检表单对话框 -->
    <el-dialog
      v-model="dialogVisible"
      :title="dialogType === 'create' ? '新建质检' : '编辑质检'"
      width="600px"
    >
      <el-form ref="formRef" :model="formData" :rules="formRules" label-width="100px">
        <el-form-item label="订单号" prop="orderNo">
          <el-input v-model="formData.orderNo" placeholder="请输入订单号" />
        </el-form-item>
        <el-form-item label="客户姓名" prop="customerName">
          <el-input v-model="formData.customerName" placeholder="请输入客户姓名" />
        </el-form-item>
        <el-form-item label="服务类型" prop="serviceType">
          <el-select v-model="formData.serviceType" placeholder="请选择服务类型" style="width: 100%;">
            <el-option label="干洗" value="dry_clean" />
            <el-option label="水洗" value="water_wash" />
            <el-option label="熨烫" value="ironing" />
            <el-option label="修补" value="repair" />
          </el-select>
        </el-form-item>
        <el-form-item label="检查项目" prop="items">
          <el-input v-model="formData.items" placeholder="请输入检查项目" />
        </el-form-item>
        <el-form-item label="检查员" prop="inspector">
          <el-input v-model="formData.inspector" placeholder="请输入检查员" />
        </el-form-item>
        <el-form-item label="检查结果" prop="result">
          <el-radio-group v-model="formData.result">
            <el-radio label="qualified">合格</el-radio>
            <el-radio label="unqualified">不合格</el-radio>
            <el-radio label="pending">待检</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="质检评分" prop="score">
          <el-input-number v-model="formData.score" :min="0" :max="100" style="width: 100%;" />
        </el-form-item>
        <el-form-item label="问题描述" v-if="formData.result === 'unqualified'">
          <el-input v-model="formData.issues" type="textarea" :rows="3" />
        </el-form-item>
        <el-form-item label="备注">
          <el-input v-model="formData.remark" type="textarea" :rows="3" />
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="dialogVisible = false">取消</el-button>
        <el-button type="primary" @click="handleSubmit" :loading="submitLoading">确定</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Plus } from '@element-plus/icons-vue'
import { quality } from '@/api/wash/index'

const loading = ref(false)
const submitLoading = ref(false)
const dialogVisible = ref(false)
const detailDialogVisible = ref(false)
const dialogType = ref('create')
const formRef = ref()
const qualityList = ref([])
const currentQuality = ref({})

// 搜索表单
const searchForm = reactive({
  orderNo: '',
  customerName: '',
  result: '',
  inspector: ''
})

// 分页
const page = reactive({
  current: 1,
  size: 20,
  total: 0
})

// 表单数据
const formData = reactive({
  id: '',
  orderNo: '',
  customerName: '',
  serviceType: '',
  items: '',
  inspector: '',
  result: 'pending',
  score: 0,
  issues: '',
  remark: ''
})

// 表单验证规则
const formRules = {
  orderNo: [{ required: true, message: '请输入订单号', trigger: 'blur' }],
  customerName: [{ required: true, message: '请输入客户姓名', trigger: 'blur' }],
  serviceType: [{ required: true, message: '请选择服务类型', trigger: 'change' }],
  items: [{ required: true, message: '请输入检查项目', trigger: 'blur' }],
  inspector: [{ required: true, message: '请输入检查员', trigger: 'blur' }],
  result: [{ required: true, message: '请选择检查结果', trigger: 'change' }]
}

const getQualityList = async () => {
  loading.value = true
  try {
    const res = await getQualityListAPI({
      page: page.current,
      size: page.size,
      ...searchForm
    })
    if (res && (res.code === 200 || res.data)) {
      const data = res.data || res
      qualityList.value = data.records || data.content || data || []
      page.total = data.total || data.totalElements || 0
    } else {
      qualityList.value = []
      page.total = 0
    }
  } catch (error) {
    console.error('获取质检列表失败:', error)
    ElMessage.warning('获取质检列表失败，请检查网络连接')
    qualityList.value = []
    page.total = 0
  } finally {
    loading.value = false
  }
}

const getServiceTypeText = (type) => {
  const typeMap = {
    dry_clean: '干洗',
    water_wash: '水洗',
    ironing: '熨烫',
    repair: '修补'
  }
  return typeMap[type] || type
}

const getResultType = (result) => {
  const types = {
    qualified: 'success',
    unqualified: 'danger',
    pending: 'warning'
  }
  return types[result] || 'info'
}

const getResultText = (result) => {
  const texts = {
    qualified: '合格',
    unqualified: '不合格',
    pending: '待检'
  }
  return texts[result] || result
}

const handleSearch = () => {
  page.current = 1
  getQualityList()
}

const handleReset = () => {
  Object.assign(searchForm, {
    orderNo: '',
    customerName: '',
    result: '',
    inspector: ''
  })
  handleSearch()
}

const handleAdd = () => {
  dialogType.value = 'create'
  resetFormData()
  dialogVisible.value = true
}

const handleEdit = (row) => {
  dialogType.value = 'edit'
  Object.assign(formData, row)
  dialogVisible.value = true
}

const handleViewDetail = (row) => {
  currentQuality.value = row
  detailDialogVisible.value = true
}

const handleRecheck = async (row) => {
  try {
    await ElMessageBox.confirm('确定要重新检查该订单吗？', '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    })
    
    const res = await recheckQuality(row.id)
    if (res && (res.code === 200 || res.success)) {
      ElMessage.success('重检申请已提交')
      getQualityList()
    }
  } catch (error) {
    if (error !== 'cancel') {
      console.error('重检失败:', error)
      ElMessage.error('重检失败')
    }
  }
}

const handleComplete = async (row) => {
  try {
    const res = await updateQualityCheck(row.id, { ...row, result: 'qualified' })
    if (res && (res.code === 200 || res.success)) {
      ElMessage.success('质检已完成')
      row.result = 'qualified'
    }
  } catch (error) {
    console.error('完成质检失败:', error)
    ElMessage.error('完成质检失败')
  }
}

const handleSubmit = async () => {
  try {
    await formRef.value.validate()
    submitLoading.value = true
    
    let res
    if (dialogType.value === 'create') {
      res = await createQualityCheck(formData)
    } else {
      res = await updateQualityCheck(formData.id, formData)
    }
    
    if (res && (res.code === 200 || res.success)) {
      ElMessage.success(dialogType.value === 'create' ? '创建成功' : '更新成功')
      dialogVisible.value = false
      getQualityList()
    }
  } catch (error) {
    console.error('操作失败:', error)
    ElMessage.error('操作失败')
  } finally {
    submitLoading.value = false
  }
}

const resetFormData = () => {
  Object.assign(formData, {
    id: '',
    orderNo: '',
    customerName: '',
    serviceType: '',
    items: '',
    inspector: '',
    result: 'pending',
    score: 0,
    issues: '',
    remark: ''
  })
}

const handleSizeChange = () => {
  getQualityList()
}

const handleCurrentChange = () => {
  getQualityList()
}

onMounted(() => {
  getQualityList()
})
</script>

<style lang="scss" scoped>
.wash-quality {
  padding: 20px;
  
  .search-card {
    margin-bottom: 20px;
  }
  
  .card-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
  }
  
  .pagination {
    display: flex;
    justify-content: center;
    margin-top: 20px;
  }
}
</style> 